package com.xian.im.modules.sensitive.load;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StopWatch;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Set;

/**
 * @program: xian-im-server
 * @description: 敏感词加载
 * @author: liru.xian
 * @create: 2021-02-23 09:31
 **/
@Slf4j
public class SensitiveLoad {
    //声明成 volatile
    private static volatile SensitiveLoad  instance;

    /** 敏感词容器 */
  private static Set<String> SENSITIVE_CONTAINER = new HashSet<>(30000);

  static {
          StopWatch stopWatch = new StopWatch("sensitive word loading");
          Resource resource = new ClassPathResource("static/sensi_words.txt");
          InputStream inputStream =null;
        BufferedReader reader = null;
          try {
              inputStream = resource.getInputStream();
              reader = new BufferedReader(new InputStreamReader(
                      inputStream, StandardCharsets.UTF_8));
                  stopWatch.start("init");
                  for(String line = reader.readLine(); line != null; line = reader.readLine()){
                      SENSITIVE_CONTAINER.add(line);
                  }
                  stopWatch.stop();
                  System.out.println("初始化敏感词 "+SENSITIVE_CONTAINER.size()+"个 加载情况 "+stopWatch.prettyPrint());
          } catch (Exception e) {
              e.printStackTrace();
          }finally{
              if (reader != null) {
                  try {
                      reader.close();
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
              }
              if (inputStream != null) {
                  try {
                      inputStream.close();
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
              }
          }
      }

    public static SensitiveLoad getInstance(){
        if(instance == null){
            synchronized (SensitiveLoad.class) {
                if(instance == null){
                    instance = new SensitiveLoad();
                }
            }
        }
        return instance;
    }

    /**
     *  敏感词集合
     * @return
     */
    public Set<String> container(){
        return SENSITIVE_CONTAINER;
    }

}
